package com.masterkey;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.*;

import com.db4o.*;

public class ChangePW extends Activity {

	EditText userName, password;
	TextView done;
	Data data;
	String siteAppString;
	Button save;
	byte[] encryptedPW;
	SecretKeySpec skeySpec;

	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.changepw);

		
		// Changed from Rasheed
		String myUserName = savedInstanceState.getString("userName");
		String myPw = savedInstanceState.getString("password");
		// ....
		
		
		userName = (EditText) findViewById(R.id.enteredUserName);
		password = (EditText) findViewById(R.id.enteredPW);
		done = (TextView) findViewById(R.id.done);

		save = (Button) findViewById(R.id.savePW);
		save.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				// siteAppString = spinner.getSelectedItem().toString();

				done.setText("Your " + siteAppString
						+ " user name and password are saved.");

				ObjectContainer oc = Db4oEmbedded.openFile(
						Db4oEmbedded.newConfiguration(), "/sdcard/MasterKeyDB");

				try {
					encrypt();
					data = new Data(siteAppString, userName.getText()
							.toString(), encryptedPW, skeySpec);

					oc.store(data);
					oc.commit();

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					oc.close();
				}
			}
		});
	}

	public static String asHex(byte buf[]) {

		StringBuffer strbuf = new StringBuffer(buf.length * 2);
		int i;

		for (i = 0; i < buf.length; i++) {

			if (((int) buf[i] & 0xff) < 0x10)
				strbuf.append("0");

			strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
		}

		return strbuf.toString();
	}

	public void encrypt() throws Exception {

		// Get the KeyGenerator
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		kgen.init(128); // 192 and 256 bits may not be available

		// Generate the secret key specs.
		SecretKey skey = kgen.generateKey();
		byte[] raw = skey.getEncoded();

		skeySpec = new SecretKeySpec(raw, "AES");

		// Instantiate the cipher
		Cipher cipher = Cipher.getInstance("AES");

		cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

		encryptedPW = cipher.doFinal(password.getText().toString().getBytes());

	}

}
